﻿using Script.ClearScript_V8;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows;
using User;
using Utils;
using Utils.Config;
using Utils.Log;

namespace FrameworkTemplate.Workers
{
    /// <summary>
    /// 供线程使用的全局变量
    /// </summary>
    public static class GLOBAL
    {
        public static Template config;
        public static ScriptManager script;
        internal static Account user;

        private static readonly string resource_lang_pattern = @"Language\\(?<language>.*?)\.xaml";
        static GLOBAL()
        {
            user = new Account();
            script = new ScriptManager();
            
            script.OnLog += Sm_OnLog;
            script.OnError += Sm_OnError;

            user.PropertyChanged += User_PropertyChanged;

            //LoadLanguage(GetCulture(Properties.Settings.Default.当前语言));

        }

        public static void Init()
        {
            //Stopwatch sw = new Stopwatch();
            //sw.Start();
            try
            {
                //读取配置项
                config = ConfigUtil.Read<Template>(Properties.Settings.Default.配置项路径);
                script.LoadStrTypes(config.脚本.引入类型);//向脚本引入配置项中类型

            }
            catch (Exception e)
            {
                Log.Error(e.ToString());
            }
            //Log.Info("初始化用时" + sw.ElapsedMilliseconds + "ms");
            //sw.Stop();

        }

        /// <summary>
        /// 设置当前语言
        /// </summary>
        /// <param name="language"></param>
        public static void SetLanguage(string language)
        {
            Properties.Settings.Default.当前语言 = language;
            Properties.Settings.Default.Save();
        }
        /// <summary>
        /// 加载指定语言
        /// </summary>
        /// <param name="culture"></param>
        public static void LoadLanguage(CultureInfo culture)
        {

            List<ResourceDictionary> dictionaryList = new List<ResourceDictionary>();
            foreach (ResourceDictionary dictionary in Application.Current.Resources.MergedDictionaries)
            {
                dictionaryList.Add(dictionary);
            }
            string requestedCulture = string.Format(@"Language\{0}.xaml", culture);
            ResourceDictionary resourceDictionary = dictionaryList.FirstOrDefault(d => d.Source.OriginalString.Equals(requestedCulture));
            if (resourceDictionary == null)
            {
                requestedCulture = string.Format(@"Language\{0}.xaml", Properties.Settings.Default.默认语言);
                resourceDictionary = dictionaryList.FirstOrDefault(d => d.Source.OriginalString.Equals(requestedCulture));
            }
            
            Application.Current.Resources.MergedDictionaries.Remove(resourceDictionary);
            Application.Current.Resources.MergedDictionaries.Add(resourceDictionary);
        }
        /// <summary>
        /// 获取所有已注册到App.xaml的语言
        /// </summary>
        /// <returns></returns>
        public static CultureInfo[] GetRegisterCultures()
        {
            var regex = new Regex(resource_lang_pattern, RegexOptions.IgnoreCase);
            var langs = new List<string>();
            foreach (ResourceDictionary dictionary in Application.Current.Resources.MergedDictionaries)
            {
                var match = regex.Match(dictionary.Source.OriginalString);
                if (match.Success)
                    langs.Add(match.Groups["language"].Value);
            }
            langs.Sort();
            return langs.Select(l => GetCulture(l)).ToArray();

        }

        /// <summary>
        /// 根据语言ID获取语言
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static CultureInfo GetCulture(string name)
        {
            try
            {
                var result = CultureInfo.GetCultureInfo(name);
                return result;
            }catch(Exception e)
            {
                Log.Error(string.Format(Resources("no_language"), name) + Environment.NewLine + e.ToString());
                return CultureInfo.GetCultureInfo(Properties.Settings.Default.默认语言);
            }
        }

        /// <summary>
        /// 只是一个缩短获取资源字符串的方法
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string Resources(string key)
        {
            return Application.Current.FindResource(key) as string;
        }
        #region 日志事件
        private static void User_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if(e.PropertyName == "name")
                Log.Info(string.Format(Resources("on_log_in"), user.name));
        }

        private static void Sm_OnError(Exception e, Microsoft.ClearScript.V8.V8ScriptEngine engine)
        {
            Log.Error(string.Format(Resources("script_error"), engine.Name) + Environment.NewLine + e.ToString());
        }

        private static void Sm_OnLog(string log)
        {
            Log.Info(log);
        }
        #endregion
        static void StopAll()
        {
            Log.Stop();
        }
    }
}
